package com.speedy.course.vm

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingSource
import androidx.paging.cachedIn
import com.speedy.course.db.AppDatabase
import com.speedy.course.db.dao.TaskDao
import com.speedy.course.db.entity.Task
import com.speedy.course.paging.TaskPagingSource
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class TaskViewModel : ViewModel() {

    val taskPageFlow = Pager(PagingConfig(10)){
        TaskPagingSource()
    }.flow.cachedIn(viewModelScope)

    private val taskDao:TaskDao = AppDatabase.getInstance().getTaskDao()


    private val _newTaskStateFlow = MutableStateFlow(Task())
    val taskStateFlow = _newTaskStateFlow.asStateFlow()

    fun loadTaskList(): PagingSource<Int,Task> {
        return TaskPagingSource()
    }


    fun saveOrUpdateTask(task: Task,onFinish:()->Unit){
        viewModelScope.launch {
            taskDao.insert(task)
            onFinish.invoke()
        }
    }


    suspend fun queryTaskByID(id:Int):Task?{
        return taskDao.queryById(id)
    }
}